package com.taobao.txc.dubbo;

import com.alibaba.dubbo.rpc.RpcContext;
import com.taobao.txc.client.aop.annotation.TxcTransaction;
import com.taobao.txc.common.TxcContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class Client {

    @TxcTransaction(timeout = 60000 * 3)
    public void business2(OrderService orderService, StockService stockService, String userId) {
        String xid = TxcContext.getCurrentXid();
        System.out.println("Begin XID: " + xid);
        OrderDO orderDO = new OrderDO(userId, 1, new Random().nextInt(5) + 1, new Timestamp(new Date().getTime()));
        orderService.createOrder(orderDO);

        stockService.updateStock(orderDO);
        throw new RuntimeException("Exception after stock updated!");
    }

    public static void main(String args[]) throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"dubbo-client.xml"});
        final OrderService orderService = (OrderService)context.getBean("OrderService");
        final StockService stockService = (StockService)context.getBean("StockService");
        final Client client = (Client)context.getBean("client");

        int previousAmount = stockService.getSum().intValue();
        final String userId = UUID.randomUUID().toString();
        try {
            client.business2(orderService, stockService, userId);
            System.out.println("Transaction is committed.");

        } catch (Exception e) {
            System.out.println("Transaction is rollbacked.");
            e.printStackTrace();
        }
        int productNumber = orderService.getSum(userId).intValue();
        int currentAmount = stockService.getSum().intValue();
        System.out.println("previousAmount: " + previousAmount);
        System.out.println("productNumber: " + productNumber);
        System.out.println("currentAmount: " + currentAmount);
        if (previousAmount == (productNumber + currentAmount)) {
            System.out.println("The result is right.");
        } else {
            System.out.println("The result is wrong.");
        }
        System.exit(0);
    }
}
